﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;

namespace TypeResolve.Loader_WinRT
{
    public static class AssemblyLoader
    {
	    public static void ConfigurePlatformBasedAssemblyLoading()
	    {
		    TypeUtils.LoadInitialAssembliesFunc = LoadCurrentAssemblies;
		    TypeUtils.LoadCurrentAssembliesFunc = LoadCurrentAssemblies;
		    TypeUtils.AssembliesLoaded = false;
	    }

	    public static List<Assembly> LoadCurrentAssemblies()
		{
			Debug.WriteLine("Loading Assemblies...");
			var assemblies = new List<Assembly>();
			//UIInvokeSync(() =>
			//{
				var folder = Package.Current.InstalledLocation;
				var files = folder.GetFilesAsync().GetAwaiter().GetResult();
				foreach (var file in files)
				{
					if (file.FileType == ".dll" || file.FileType == ".exe")
					{
						var assemblyName = new AssemblyName(file.DisplayName);
						try
						{
							assemblies.Add(Assembly.Load(assemblyName));
							Debug.WriteLine("Loaded assembly: " + file.DisplayName);
						}
						catch (Exception ex)
						{
							Debug.WriteLine("Failed to load assembly! " + file.DisplayName + "\nError: " + ex);
						}
					}
				}
			
			return assemblies;
		}
	}
}
